const auth = require('../config/auth'),
      MEMBER = 'rf_member',
      TOKEN = 'rf_token',
      TOKENTIME = 'rf_tokenTime',
      REFRESH = 'rf_refreshToken';

async function checkAuth(authName) {
  await wx.getSetting({
    success(res) {
      // 如果用户未接受或拒绝过此权限，会弹窗询问用户，用户点击同意后方可调用接口
      /*if (!res.authSetting['scope.' + authName]) {
        getAuth(authName);
      }*/
      return res.authSetting['scope.' + authName];
    }
  });
}

function getAuth(authName) {
  wx.authorize({
    scope: 'scope.' + authName,
    success () {  // 如果用户已授权，可以直接调用接口
      // 已经同意使用功能，后续调用接口不会弹窗询问
      wx[auth[authName]]();
    },
    fail () { // 如果用户已拒绝授权，则不会出现弹窗，需兼容用户拒绝授权的场景
      
    }
  });
}

// 检测登录状态，返回 true / false
async function hasLogin() {
  let rawToken = wx.getStorageSync(TOKEN),
      tokenTime = wx.getStorageSync(TOKENTIME),
      index = rawToken.lastIndexOf('_'),
      token = rawToken.substring(0, index),
      timestamp = Number(rawToken.substring(index + 1));

  if (!token) return false;
  /*if (checkAuth('userInfo')) {
    wx.checkSession({
      fail() {
        return false;
      }
    });
  } else {
    return false;
  }*/
  else if (timestamp + tokenTime <= wx.time.curUnix()) {
    return await refreshToken();
  }
  else return true;
}

async function refreshToken() {
  let res = await wx.util.request('auth.refresh', {
    body: {
      refresh_token: wx.getStorageSync(REFRESH),
      group: 'tinyShopWechatMp'
    }
  });
  if (res) {
    setLoginState(res);
    return true;
  } else {
    return false;
  }
  /*wx.util.request('auth.refresh', {
    body: {
      refresh_token: wx.getStorageSync(REFRESH),
      group: 'tinyShopWechatMp'
    }
  }).then(res => {
    setLoginState(res);
    return true;
  }).catch(err => {
    console.log(err);
    return false;
  });*/
}

function register(info) {
  wx.util.request('auth.register', {
    body: {
      group: 'tinyShopWechatMp',
      nickname: info.name,
      mobile: info.mobile,
      password: info.pwd,
      password_repetition: info.pwd2,
      code: info.code
    }
  }).then(memberInfo => {
    // 更新本地登录态
    setLoginState(memberInfo);
    // 绑定小程序登录信息
    let regInfo = wx.getStorageSync('rf_userRegInfo') || '';
    wx.util.request('auth.bind', {
      body: {
        oauth_client: 'wechatMp',
        oauth_client_user_id: regInfo.openId,
        unionid: regInfo.unionId || '',
        nickname: regInfo.nickName || '',
        gender: regInfo.gender || '',
        head_portrait: regInfo.avatarUrl || '',
        country: regInfo.country || '',
        province: regInfo.province || '',
        city: regInfo.city || '',
      }
    }).then(bindRes => {
      wx.removeStorageSync('rf_userRegInfo');
    }).catch(err => {
      console.log(err);
    });
  }).catch(err => {
    console.log(err);
  });
}

function login(page) {
  wx.login({
    success(wxLogin) {
      let code = wxLogin.code;
      if (code) {
        wx.getUserInfo({
          success(userInfo) {
            wx.util.request('auth.login', {
              body: {
                code: code,
                signature: userInfo.signature,
                encryptedData: userInfo.encryptedData,
                rawData: userInfo.rawData,
                iv: userInfo.iv,
              }
            }).then(member => {
              // 需要用户注册
              if (!member.login) {
                wx.setStorageSync('rf_userRegInfo', member.user_info);
                wx.navigateTo({
                  url: '/pages/user/register',
                });
                return;
              }
              setLoginState(member.user_info);
              if (page) {
                page.onShow();
              }
            }).catch(err => {
              console.log(err);
            });
          },
          fail(e) {
            console.log(e);
          }
        })
      } else {
        console.log('登录失败：' + wxLogin.errMsg);
      }
    },
    fail(e) {
      console.log(e);
    }
  });
}

async function getMemberInfo() {
  let info = await wx.util.request('user.info.detail');
  if (info) {
    wx.setStorageSync(MEMBER, info);
    return info;
  } else {
    console.log(info);
  }
}

function setLoginState(loginData) {
  wx.setStorageSync(TOKEN, loginData.access_token);
  wx.setStorageSync(TOKENTIME, loginData.expiration_time);
  wx.setStorageSync(REFRESH, loginData.refresh_token);
  wx.setStorageSync(MEMBER, loginData.member);
}

function logout() {
  wx.removeStorageSync(TOKEN);
  wx.removeStorageSync(TOKENTIME);
  wx.removeStorageSync(REFRESH);
  wx.removeStorageSync(MEMBER);
}

module.exports = {
  checkAuth: checkAuth,
  getAuth: getAuth,
  hasLogin: hasLogin,
  register: register,
  login: login,
  memberInfo: getMemberInfo,
  logout: logout,
}